/**
 * AnswerServiceImpl是AnswerService接口的实现类，负责处理与答案相关的业务逻辑。
 */
package org.inspiration.dudu.content.service.impl;

import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import org.inspiration.dudu.common.constant.RedisConstant;
import org.inspiration.dudu.common.util.FileUtil;
import org.inspiration.dudu.common.util.RedisUtil;
import org.inspiration.dudu.content.mapper.AnswerMapper;
import org.inspiration.dudu.content.model.dto.AnswerDTO;
import org.inspiration.dudu.content.model.entity.AnswerEntity;
import org.inspiration.dudu.content.model.vo.AnswerVO;
import org.inspiration.dudu.content.service.AnswerService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class AnswerServiceImpl implements AnswerService {

    private final AnswerMapper answerMapper;
    private final RedisUtil redisUtil;

    private final RabbitTemplate rabbitTemplate;

    @Value("${dudu.rabbitmq.exchanges.like-exchange.name}")
    private String likeExchangeName;

    @Value("${dudu.rabbitmq.exchanges.like-exchange.queues.answer-like-queue.routing-key}")
    private String answerLikeRoutingKey;

    /**
     * 根据问题ID以升序获取所有答案
     * 
     * @param questionId 问题ID
     * @param pageNum 当前页码
     * @param pageSize 每页大小
     * @return 答案视图对象列表
     */
    @Override
    public List<AnswerVO> getAnswersByQuestionIdOrderByASC(String questionId, Integer pageNum, Integer pageSize) {
        List<AnswerEntity> list = answerMapper.getAnswersByQuestionIdOrderByASC(questionId, (pageNum - 1) * pageSize, pageSize);
        List<AnswerVO> res = new ArrayList<>();
        for (AnswerEntity entity : list) {
            res.add(transToVO(entity));
        }
        return res;
    }

    /**
     * 将AnswerEntity转换为AnswerVO
     * 
     * @param answerEntity 答案实体
     * @return 答案视图对象
     */
    @Override
    public AnswerVO transToVO(AnswerEntity answerEntity) {
        AnswerVO answerVO = new AnswerVO();
        BeanUtils.copyProperties(answerEntity, answerVO);
        String content = FileUtil.readStringFromFile(answerEntity.getContentFilePath());
        answerVO.setContent(content);
        return answerVO;
    }

    /**
     * 增加答案的点赞数
     * 
     * @param contentId 答案内容ID
     */
    @Override
    public void increaseLikeCount(String contentId) {
        String key = RedisConstant.ANSWER_KEY_PREFIX + contentId;
        redisUtil.incrementHashFieldWithLua(key, "likeCount");

        // 异步更新数据库
        Map<String, Object> map = new HashMap<>();
        map.put("contentId", contentId);
        map.put("action", "like");
        rabbitTemplate.convertAndSend(likeExchangeName, answerLikeRoutingKey, map);
    }

    /**
     * 减少答案的点赞数
     * 
     * @param contentId 答案内容ID
     */
    @Override
    public void decreaseLikeCount(String contentId) {
        String key = RedisConstant.ANSWER_KEY_PREFIX + contentId;

        redisUtil.decrementHashFieldWithLua(key, "likeCount");

        // 异步更新数据库
        Map<String, Object> map = new HashMap<>();
        map.put("contentId", contentId);
        map.put("action", "unlike");
        rabbitTemplate.convertAndSend(likeExchangeName, answerLikeRoutingKey, map);
    }


    /**
     * 根据内容ID获取用户ID
     * 
     * @param contentId 答案内容ID
     * @return 用户ID
     */
    @Override
    public Long getUserIdByContentId(String contentId) {
        return getAnswerByContentId(contentId).getUserId();
    }

    /**
     * 根据内容ID获取答案
     * 
     * @param contentId 答案内容ID
     * @return 答案视图对象
     */
    @Override
    public AnswerVO getAnswerByContentId(String contentId) {
        AnswerEntity answerEntity = redisUtil.queryHashCache(
                RedisConstant.ANSWER_KEY_PREFIX,
                contentId,
                AnswerEntity.class,
                answerMapper::getAnswerByContentId,
                60L,
                TimeUnit.SECONDS

        );
        return transToVO(answerEntity);
    }

    /**
     * 增加答案的收藏数
     * 
     * @param contentId 答案内容ID
     */
    @Override
    public void increaseFavoriteCount(String contentId) {
        answerMapper.increaseFavoriteCount(contentId);
        String key = RedisConstant.ANSWER_KEY_PREFIX + contentId;
        redisUtil.deleteKey(key);
    }

    /**
     * 减少答案的收藏数
     * 
     * @param contentId 答案内容ID
     */
    @Override
    public void decreaseFavoriteCount(String contentId) {
        String key = RedisConstant.ANSWER_KEY_PREFIX + contentId;
        answerMapper.decreaseFavoriteCount(contentId);
        redisUtil.deleteKey(key);
    }



    /**
     * 将AnswerDTO转换为AnswerEntity
     * 
     * @param answerDTO 答案数据传输对象
     * @param contentFilePath 内容文件路径
     * @param uuid 答案ID
     * @return 答案实体
     */
    @Override
    public AnswerEntity transToEntity(AnswerDTO answerDTO, String contentFilePath, String uuid) {
        AnswerEntity answerEntity = new AnswerEntity();
        BeanUtils.copyProperties(answerDTO, answerEntity);
        answerEntity.setContentFilePath(contentFilePath);
        answerEntity.setId(uuid);
        return answerEntity;
    }

    /**
     * 创建答案
     * 
     * @param answerEntity 答案实体
     */
    @Override
    public void createAnswer(AnswerEntity answerEntity) {
        answerMapper.createAnswer(answerEntity);
    }

    /**
     * 增加答案的评论数
     * 
     * @param contentId 答案内容ID
     */
    @Override
    public void increaseCommentCount(String contentId) {
        answerMapper.increaseCommentCount(contentId);
        String key = RedisConstant.ANSWER_KEY_PREFIX + contentId;
        redisUtil.deleteKey(key);
    }

    /**
     * 根据问题ID以降序获取所有答案
     * 
     * @param questionId 问题ID
     * @param pageNum 当前页码
     * @param pageSize 每页大小
     * @return 答案视图对象列表
     */
    @Override
    public List<AnswerVO> getAnswersByQuestionIdOrderByDESC(String questionId, Integer pageNum, Integer pageSize) {
        List<AnswerEntity> list = answerMapper.getAnswersByQuestionIdOrderByDESC(questionId, (pageNum - 1) * pageSize, pageSize);
        List<AnswerVO> res = new ArrayList<>();
        for (AnswerEntity entity : list) {
            res.add(transToVO(entity));
        }
        return res;
    }

    /**
     * 根据ID获取答案
     * 
     * @param id 答案ID
     * @return 答案视图对象
     */
    @Override
    public AnswerVO getAnswerById(String id) {
        return answerMapper.getAnswerById(id);
    }

    @Override
    public List<AnswerVO> getAnswersByUserIdOrderByDESC(Long userId, Integer pageNum, Integer pageSize) {
        List<AnswerEntity> list = answerMapper.getAnswersByUserIdOrderByDESC(userId, (pageNum - 1) * pageSize, pageSize);
        List<AnswerVO> res = new ArrayList<>();
        for (AnswerEntity entity : list) {
            res.add(transToVO(entity));
        }
        return res;
    }


}
